﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;

namespace SohuWeb.Models {
    public class Config {
        private XmlDocument xmlDoc;
        static string confFile = AppDomain.CurrentDomain.BaseDirectory + "Config.xml";
        public string CSVPath { get; set; }
        public string CSVGatherTime { get; set; }
        public string NewDataGatherTime { get; set; }
        public string ComputeTime { get; set; }

        public void SaveConfig() {
            XmlNode root = xmlDoc.SelectSingleNode("Config");
            XmlElement el = (XmlElement)root.SelectSingleNode("CSVPath");
            el.InnerText = CSVPath;
            el = (XmlElement)root.SelectSingleNode("CSVGatherTime");
            el.InnerText = CSVGatherTime;
            el = (XmlElement)root.SelectSingleNode("NewDataGatherTime");
            el.InnerText = NewDataGatherTime;
            el = (XmlElement)root.SelectSingleNode("ComputeTime");
            el.InnerText = ComputeTime;
            xmlDoc.Save(confFile);
        }

        public Config() {
            LoadXml();
        }

        private void LoadXml() {
            if (!File.Exists(confFile)) {
                xmlDoc = InitConfigFile(confFile);
            } else {
                xmlDoc = new XmlDocument();
                xmlDoc.Load(confFile);
            }

            XmlNode root = xmlDoc.SelectSingleNode("Config");
            XmlElement el = (XmlElement)root.SelectSingleNode("CSVPath");
            CSVPath = el.InnerText;
            el = (XmlElement)root.SelectSingleNode("CSVGatherTime");
            CSVGatherTime = el.InnerText;
            el = (XmlElement)root.SelectSingleNode("NewDataGatherTime");
            NewDataGatherTime = el.InnerText;
            el = (XmlElement)root.SelectSingleNode("ComputeTime");
            ComputeTime = el.InnerText;
        }

        private XmlDocument InitConfigFile(string xmlfile) {
            XmlDocument doc = new XmlDocument();
            XmlNode node = doc.CreateNode(XmlNodeType.Element, "Config", "");
            doc.AppendChild(node);
            Hashtable tab = new Hashtable();
            tab.Add("CSVPath", null);
            tab.Add("CSVGatherTime", "0505");
            tab.Add("NewDataGatherTime", "0510");
            tab.Add("ComputeTime", "0600");
            foreach (DictionaryEntry  de in tab) {
                XmlElement el = doc.CreateElement((string)de.Key);
                el.InnerText = (string)de.Value;
                node.AppendChild(el);
            }
            doc.Save(xmlfile);
            return doc;
        }
    }
}